# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.quanqiuzhifu.net/SPThreePayApi.aspx'

APP_CONF = {
    'Z1001': {
        'API_KEY': 'FgCC8aEhJa38aaUxXJblPzE8L'
    },
    'Z1002': {
        'API_KEY': 'lRd2fXzlnv8pMDMJJzcTZ4nwh'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['signData']
    params.pop('signData')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("threepay sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def build_html(code_url):
    html = u"<head><title>请打开微信扫码支付</title></head>"
    html += u"<body><div style='text-align: center'><span>请将下面二维码截图，然后用微信扫一扫</span></div>"
    html += "<div style='text-align: center'><img src='{}' /></div>".format(code_url)
    html += "</body>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info.get('service')  # wechat or alipay
    if service == 'wechat':
        pay_type = 'pay_weixin_scan'
    else:
        pay_type = 'pay_alipay_scan'
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = {
        'subject': 'goods',
        'total_fee': int(pay_amount * 100),
        'pay_type': pay_type,
        'mchNo': app_id,
        'version': '001',
        'mchorderid': str(pay.id),
        'showurl': '{}/pay/api/{}/threepay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    parameter_dict['callback_url'] = '{}/pay/api/{}/threepay/'.format(
        settings.NOTIFY_PREFIX, settings.NOTIFY_PATH)
    _LOGGER.info('threepay charge params:{}'.format(parameter_dict))
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    response = requests.post(_GATEWAY, data=json.dumps(parameter_dict, separators=(',', ':')), headers=headers,
                             timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        res_obj = json.loads(response.text)
        if service == 'wechat':
            charge_resp.update({
                'charge_info': build_html(res_obj['code_img_url']),
            })
        else:
            charge_resp.update({
                'charge_info': res_obj['code_url'],
            })
        _LOGGER.info("threepay data after charge: %s", res_obj)
    else:
        _LOGGER.warn('threepay data error, status_code: %s', response.status_code)
    return charge_resp


def check_notify_sign(request):
    data = dict(request.GET.iteritems())
    _LOGGER.info("threepay notify data: %s", data)
    app_id = data['channel']
    api_key = _get_api_key(app_id)
    pay_id = data['OrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('threepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_no = data['pdorderid']
    total_fee = float(data['fee']) / 100

    extend = {
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    _LOGGER.info('threepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    res = order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
